package com.hanxiaozhang.no10leetcode.array;

import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 * 给一个字符串数组，将所有易位构词按组分到一起
 * 实例:
 * 输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
 * 输出: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ]
 * 注意: 所给的数组中所有字符均为小写 答案的输出顺序无所谓
 * <p>
 * 思路：
 * 1. 将数组中元素转换成字符数组，然后对字符数组排序
 * 2. 将排序后的字符数组转换成String，存入Map中，key：排序的字符数组，value：原数组中元素
 * 3. 遍历Map，返回结果
 *
 * @author hanxinghua
 * @create 2024/1/18
 * @since 1.0.0
 */
public class No49GroupAnagrams {

    public static void main(String[] args) {

        String[] arr = {"eat", "tea", "tan", "ate", "nat", "bat"};

        System.out.println(method1(arr));

    }

    private static List<List<String>> method1(String[] arr) {
        List<List<String>> result = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>(8);
        for (int i = 0; i < arr.length; i++) {
            char[] chars = arr[i].toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            if (map.containsKey(key)) {
                map.get(key).add(arr[i]);
            } else {
                List<String> list = new ArrayList<>();
                list.add(arr[i]);
                map.put(key, list);
            }
        }
        result.addAll(map.values());
        return result;
    }
}
